package org.jeecg.modules.api.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.encryption.MyAesEncryptUtil;
import org.jeecg.common.util.rest.RestTemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 双因素认证接口处理类
 */
@Api(tags = "双因素认证接口")
@RestController
@RequestMapping("/towfactor/api")
@Slf4j
public class TowFactorApiController {

    private static final Logger logger = LoggerFactory.getLogger(TowFactorApiController.class);

    //双因素认证服务器地址
    @Value("${qixin.imas.url}")
    private String iAMSAuthUrl;
    //服务器ID(服务信息中序列号)
    @Value("${qixin.imas.serviceId}")
    private String SERVICEID;

    //共享秘钥
    private static final String SHAREDSECRET = "GUZAUKxPjKSkG4GKCJfOTw==";
    //设置名称
    private static final String CLIENTNAME = "gys";

    //使用AES-128-CBC加密模式，key需要为16位,key和iv可以相同！
    private static final String KEY = "00000GYS20210808";

    private static final String IV = "00000GYS20210808";

    /**
     * 签收环节验证KEY是否正确 -- 3.0版本
     */
    @ApiOperation(value = "验证KEY是否正确")
    @AutoLog(value = "询价供应商-通过询价id查询可供商品")
    @GetMapping("checkKey")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pwd", value = "密钥", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userid", value = "用户id", dataType = "String", paramType = "query"),
    })
    @ApiOperationSupport(ignoreParameters = "params")
    public Result<?> checkXjmy(@RequestParam Map<String, String> params) {

        if(StrUtil.isBlank((String) params.get("pwd"))){
            return Result.error("动态密钥不能为空");
        }
        if(StrUtil.isBlank((String) params.get("userid"))){
            return Result.error("用户id不能为空");
        }

/*
        if (true){
            return Result.OK("密钥验证成功","OK");
        }
*/

        String tmpPwd = null;
        String password = params.get("pwd");
        String loginCode = params.get("userid");
        try {
            tmpPwd = MyAesEncryptUtil.encrypt_pkcs(password,KEY,IV).trim();
        } catch (Exception e) {
            return Result.error("动态密钥不正确");
        }

        try {

            JSONObject jsonParam = new JSONObject();
            jsonParam.put("clientName", CLIENTNAME);
            jsonParam.put("sharedSecret", SHAREDSECRET);
            jsonParam.put("loginCode", loginCode);
            jsonParam.put("loginWord", tmpPwd);
            jsonParam.put("authType", "2");
            jsonParam.put("deviceType", "6");
            jsonParam.put("serviceId", SERVICEID);

            int pre = (int) System.currentTimeMillis();
            logger.info("开标认证开始：{}", loginCode);
            String res = null;
            try {
                res = RestTemplateUtil.doIgnoreVerifySSLPost(iAMSAuthUrl, jsonParam);
            } catch (KeyManagementException e) {
                e.printStackTrace();
                return Result.error("密钥认证错误");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                return Result.error("密钥认证错误");
            }

            JSONObject jsonObject = (JSONObject) JSON.parse(res);
            logger.info("认证服务返回：{}", jsonObject.toJSONString());
            ;
            int statusCode = Integer.parseInt(jsonObject.get("code").toString());
            if (statusCode > 200) {
                String errMsg = "";
                switch (statusCode) {
                    case 202:
                        errMsg = "用户不存在";
                        break;
                    case 203:
                        errMsg = "认证设备信息错误";
                        break;
                    case 210:
                        errMsg = "认证设备地址错误";
                        break;
                    case 204:
                        errMsg = "认证服务器配置错误";
                        break;
                    case 205:
                        errMsg = "密码/密钥错误";
                        break;
                    case 206:
                        errMsg = "密码为空";
                        break;
                    case 207:
                        errMsg = "参数错误";
                        break;
                    case 208:
                        errMsg = "服务ID错误";
                        break;
                    default:
                        errMsg = "challenge请求";
                }
                return Result.error(errMsg);
            }

            int finaltime = (int) System.currentTimeMillis();
            int timeConsuming = (finaltime - pre) / 1000;
            logger.info("开标认证结束：{}，耗时：{} 秒", loginCode, timeConsuming);


        } catch (NumberFormatException ex) {
            ex.printStackTrace();
            logger.error("statusCode转换错误！");
            return Result.error("statusCode转换错误");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("密钥认证超时！");
            return Result.error("密钥认证超时！");
        }

        return Result.OK("密钥验证成功","OK");
    }


}
